package com.keepers.repair.adapter

import android.annotation.SuppressLint
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import com.keepers.repair.R
import com.keepers.repair.model.TaskModel
import com.keepers.repair.utils.Api
import com.keepers.repair.utils.getUser
import org.jetbrains.anko.alert
import org.jetbrains.anko.find
import org.jetbrains.anko.noButton
import org.jetbrains.anko.yesButton

class TaskAdapter(private val list: List<TaskModel>) : RecyclerView.Adapter<TaskAdapter.ViewHolder>() {

    override fun getItemCount() = list.size
    override fun onCreateViewHolder(viewGroup: ViewGroup, position: Int): ViewHolder {
        val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_task, viewGroup, false)
        return ViewHolder(view)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = list[position]
        holder.name.text = item.TaskName
        holder.time.text = item.DataTime
        holder.user.text = "${item.Name} - ${item.UserName}"
        holder.place.text = item.PlaceName
        holder.line.text = item.LineName
        holder.button.setOnClickListener { view ->
            val user = getUser(view.context)
            if (user == null) {
                view.context.alert("用户信息出错，请重新登录") {
                    yesButton {}
                }
                return@setOnClickListener
            }
            view.context.alert("领取此任务？") {
                title = "任务"
                yesButton {
                    Api.makeRepair(
                        user.Gid,
                        user.GroupGid!!,
                        item.GPSID,
                        item.TaskName,
                        user.Gid
                    ) { result ->
                        if (result) {
                            view.context.alert("领取成功") { yesButton {} }.show()
                        } else {
                            view.context.alert("领取失败") { yesButton {} }.show()
                        }
                    }
                }
                noButton {}
            }.show()
        }
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val name = view.find<TextView>(R.id.item_task_name)
        val time = view.find<TextView>(R.id.item_task_time)
        val user = view.find<TextView>(R.id.item_task_user)
        val place = view.find<TextView>(R.id.item_task_place)
        val line = view.find<TextView>(R.id.item_task_line)
        val button = view.find<Button>(R.id.item_task_button)
    }
}
